package controllers

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"io/ioutil"
	"net"
	"net/http"
	"strings"
	"time"
)

type BarCodeController struct {
	ApiBaseController
}

// @router /getimagebean [post]
func (this *BarCodeController) GetImageBean() {
	bean := BaseBean{}
	storeCode := this.GetString("store_code", "")
	if len(storeCode) == 0 {
		bean.Code = "-1"
		bean.Message = "store_code不能为空"
		this.Data["json"] = bean
		this.ServeJSON()
		return
	}

	if !doNext(storeCode){
		bean.Code = "-1"
		bean.Message = "查询失败"
		this.Data["json"] = bean
		this.ServeJSON()
		return
	}

	var list []ImageBean
	o := orm.NewOrm()
	var imageBeanListSql string = fmt.Sprintf("SELECT barcode_data.title, barcode_data.content, barcode_data.image_url from barcode_data WHERE barcode_data.enable = \"%s\" ", "Y")
	beego.Debug(imageBeanListSql)
	imageBeanListNum, imageBeanListErr := o.Raw(imageBeanListSql).QueryRows(&list)
	if imageBeanListErr != nil || imageBeanListNum <= 0 {
		bean.Code = "-1"
		bean.Message = "查询失败"
		this.Data["json"] = bean
		this.ServeJSON()
		return
	}
	beego.Debug(list)
	this.Data["json"] = map[string]interface{}{
		"code": "0",
		"msg":  "SUCCESS",
		"data": list[0],
	}
	this.ServeJSON()
	return
}

func doNext(storeCode string) bool{
	client := &http.Client{
		Transport: &http.Transport{
			Dial: func(netw, addr string) (net.Conn, error) {
				conn, err := net.DialTimeout(netw, addr, time.Second*4)    //设置建立连接超时
				if err != nil {
					return nil, err
				}
				conn.SetDeadline(time.Now().Add(time.Second * 4))    //设置发送接受数据超时
				return conn, nil
			},
			ResponseHeaderTimeout: time.Second * 4,
		},
	}

	params := fmt.Sprintf("store_code=%s", storeCode)
	req, err := http.NewRequest("POST",
		"http://api.miaofutech.com/mfapi/couponcode/check_diff_trades",
		strings.NewReader(params))
	if err != nil {
		return false
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	resp, err := client.Do(req)
	if err != nil {
		return false
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return false
	}
	beego.Debug(string(body))
	if string(body) == "Y"{
		return true
	}else{
		return false
	}
	return false
}

type ImageBean struct {
	Title    string `json:"title"`
	Content  string `json:"content"`
	ImageUrl string `json:"image_url"`
}
